//
//  BranPage_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/28.
//
//


/*
 owner:cy
 update:2017年03月28日11:47:01
 info: 品牌详情界面
 viewmodel: BranPage_Vm
 */
import RxSwift
import UtilCore
import RickonCore
import BrandonCore

class BranPage_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    /// 品牌名称
    @IBOutlet weak var brname_Lb: UILabel!
    /// 商品数量
    @IBOutlet weak var pdcount_Lb: UILabel!
    ///0-末收藏 1-已收藏
    @IBOutlet weak var colflag_Btn: UIButton!
    ///收藏个数
    @IBOutlet weak var colcount_Lb: UILabel!
    
    ///品牌简介
    @IBOutlet weak var brinfo_Lb: UILabel!
    /// label的默认高度
    @IBOutlet weak var brinfo_Height_Lc: NSLayoutConstraint!
    @IBOutlet weak var brinfourl_ImgV: UIImageView!
    
    @IBOutlet weak var brlogourl_ImgV: UIImageView!
    
    @IBOutlet weak var newProducts_Cv: UICollectionView!

    @IBOutlet weak var newProducts_Height_Lc: NSLayoutConstraint!
    
    @IBOutlet weak var seperateLine_V: UIView!
    @IBOutlet weak var content_Sv: UIScrollView!
    ///查看更多
    @IBOutlet weak var ckgd_Btn: UIButton!
    /// 底部查看更多 ,如果查回来的新品上架商品为空的时候需要隐藏 底部查看更多区域
    @IBOutlet weak var footer_V: UIView!
    
    @IBOutlet weak var product_Content_V: UIView!
    @IBOutlet weak var spread_Btn: UIButton!
    let spreadHeight:CGFloat = 40.0
    /// 展开按钮的高度
    @IBOutlet weak var spread_Height_Lc: NSLayoutConstraint!
    var productList = [HpProductModel]() {
        didSet {
            self.newProducts_Cv.reloadData()
        }
    }
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var brid:String?
    var manageVm:BranPage_Vm?
    
    var brandModel:BrandPageModel?
    
    /// 品牌描述每行的高度
    var singalLineHeight:CGFloat{
        get{
            let height = "".heightWithConstrainedWidth(width: self.brinfo_Lb.frame.size.width, font: UIFont(name: Theme.fontName, size: 12)!)
            return height
        }
    }
    /// 默认最高的高度
    var maxLineHeight:CGFloat{
        get{
            return self.singalLineHeight * 2
        }
    }
    var brinfoHeight:CGFloat?
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        upddateViewByBrandItem(BrandPageModel(json: "")!)
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.seperateLine_V.backgroundColor = Theme.v.separate_Line
        self.ckgd_Btn.changeBorderColor(Theme.robb.brandPage.ckgd_Border, cornerRadius: 6.0)
        self.brlogourl_ImgV.changeBorderColor(Theme.robb.brandPage.brlogourl_Border, cornerRadius: 1, borderWidth: 1)
        ///隐藏滑动条
        self.newProducts_Cv.showsVerticalScrollIndicator = false
        self.content_Sv.showsVerticalScrollIndicator = false
        self.newProducts_Height_Lc.constant = 442*self.view.frame.size.width/750 + 2
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.manageVm = BranPage_Vm(refreshTriger: rx.sentMessage(#selector(BranPage_Vc.viewWillAppear)).map { _ in () }.filter{ _ in
            self.brid != nil
            }.map{self.brid!})
        self.manageVm?
            .brandPageItem
            .subscribe(onNext: {[unowned self] (brandPageItem) in
                self.upddateViewByBrandItem(brandPageItem)
            })
            .disposed(by: disposeBag)
        self.manageVm?
            .loading
            .asObservable()
            .bindTo(self.view.rx_loading)
            .disposed(by: disposeBag)
        self.manageVm?
            .error
            .bindTo(self.view.rx_error)
            .disposed(by: disposeBag)
        self.manageVm?
            .brCollectionSuccess
            .subscribe(onNext: {[unowned self] (cid) in
                if cid.characters.count > 0{
                    ////表示收藏成功应该加1
                    if let model = self.brandModel{
                        model.glBrandRepertory.colcount = model.glBrandRepertory.colcount + 1
                    }
                }else{
                    ////表示取消收藏 应该减1
                    if let model = self.brandModel, model.glBrandRepertory.colcount > 0{
                        model.glBrandRepertory.colcount = model.glBrandRepertory.colcount - 1
                    }
                }
                self.colflag_Btn.isSelected = cid.characters.count > 0
                self.brandModel?.glBrandRepertory.cid = cid
                self.updateItemView()
            })
            .addDisposableTo(disposeBag)
        self.colflag_Btn
            .rx.tap
            .auth_validation("0")
            .subscribe(onNext: { [unowned self] ( isok ) in
                if let brandModel = self.brandModel,isok{
                    /// 表示已经收藏
                    if self.colflag_Btn.isSelected{
                        self.manageVm?.delusBrCollectionSubject.onNext(brandModel.glBrandRepertory.cid)
                    }else{
                        ///表示 未收藏
                        if let user  = AppData.loginedUser {
                            self.manageVm?.addusBrCollectionSubject.onNext((userid: user.userid, brid:"\(brandModel.glBrandRepertory.brid)"))
                        }
                    }
                }
            }).disposed(by: disposeBag)
        self.spread_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.spread_Btn.isSelected = !self.spread_Btn.isSelected
                if self.spread_Btn.isSelected{
                    if let brinfoHeight = self.brinfoHeight, brinfoHeight > self.maxLineHeight{
                        self.brinfo_Height_Lc.constant = brinfoHeight + brinfoHeight*3/14
                    }else{
                        self.brinfo_Height_Lc.constant = self.maxLineHeight
                    }
                }else{
                    self.brinfo_Height_Lc.constant = self.maxLineHeight
                }
            }).disposed(by: disposeBag)
        
        self.ckgd_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                if let brandModel = self.brandModel{
                    _ = "searchproducts".openURL(["brid":brandModel.glBrandRepertory.brid,"title":brandModel.glBrandRepertory.brname])
                }
            }).disposed(by: disposeBag)
    }
}
extension BranPage_Vc{
    /// 通过model 更新界面
    func upddateViewByBrandItem(_ brandItem:BrandPageModel){
        self.brandModel = brandItem
        updateItemView()
    }
    ///更新界面
    func  updateItemView(){
        if let brandItem = self.brandModel {
            let brandModel = brandItem.glBrandRepertory
//            self.brinfo_Lb.text = brandModel.brinfo
            self.brinfo_Lb.setLineSpacing(text: brandModel.brinfo, lineSpacing: 3)
            self.brname_Lb.text = brandModel.brname
            self.updateBrinfoLbHeight(brandModel.brinfo)
            self.brinfourl_ImgV.setUrlImage(brandModel.brinfourl)
            self.brlogourl_ImgV.setUrlImage(brandModel.brlogourl)
            //0-末收藏 1-已收藏
            self.colflag_Btn.isSelected = brandModel.cid.characters.count > 0
            /// 如果0个人收藏则隐藏
            self.colcount_Lb.isHidden = brandModel.colcount == 0
            self.colcount_Lb.text = "\(brandModel.colcount)人已收藏"
            self.pdcount_Lb.isHidden = brandModel.pdcount == 0
            self.pdcount_Lb.text = "共\(brandModel.pdcount)件商品"
            self.productList = brandItem.newPdList
        }
    }
    // 计算品牌简介label的高度
    func updateBrinfoLbHeight(_ brinfo:String) -> Void {
        let height = brinfo.heightWithConstrainedWidth(width: self.brinfo_Lb.frame.size.width, font: UIFont(name: Theme.fontName, size: 12)!)
        self.brinfoHeight = height
        if height <= self.maxLineHeight {
            self.brinfo_Height_Lc.constant = height
            self.spread_Btn.isHidden = true
            self.spread_Height_Lc.constant = 0.0
        }else{
            self.spread_Btn.isHidden = false
            self.brinfo_Height_Lc.constant = self.maxLineHeight
            self.spread_Height_Lc.constant = spreadHeight
        }
    }
}
// MARK: - UICollectionViewDataSource
extension BranPage_Vc:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        if self.productList.count > 0 {
            self.product_Content_V.isHidden = false
            self.footer_V.isHidden = false
        }else{
            self.footer_V.isHidden = true
            self.product_Content_V.isHidden = true
        }
        return self.productList.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HpProduct_Item_H_CCell", for: indexPath) as!HpProduct_Item_H_CCell
        let item  = self.productList[indexPath.row]
        cell.item = item
        return cell
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return 1
    }
}
extension BranPage_Vc:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let model = self.productList[indexPath.row]
        _ = "productdetail".openURL(["pdid":"\(model.pdid)"])

    }
}

extension BranPage_Vc:UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        return HpProduct_Item_H_CCell.cellSize
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        return HpProduct_Item_H_CCell.cellEdgeInsets
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        
        return HpProduct_Item_H_CCell.lineSpacing
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return HpProduct_Item_H_CCell.interitemSpacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        return CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
        switch section {
        case 0:
            return CGSize.zero
        case 1:
            return CGSize.zero
        default:
            return CGSize.zero
        }
    }
}
